//
//  ViewController.m
//  DownLoadByNSURLSession
//
//  Created by @Zs on 16/4/17.
//  Copyright © 2016年 @Zs. All rights reserved.
//

#import "ViewController.h"
#import "MBProgressHUD+MJ.h"
#import "MusicPlaerViewController.h"


@interface ViewController ()<NSURLSessionDownloadDelegate>
{
     NSURLSessionDownloadTask *_downloadTask;
}


@property (weak, nonatomic) IBOutlet UIView *musicToolView;

@property (weak, nonatomic) IBOutlet UIView *tabbarView;

@property (strong, nonatomic) IBOutlet UISwipeGestureRecognizer *swipeMusic;

@property (strong, nonatomic) IBOutlet UIPanGestureRecognizer *panMusic;

@property (nonatomic, strong) UIView *musicView;

@end

@implementation ViewController

- (UIView *)musicView
{
    if (!_musicView) {
        _musicView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height)];
        _musicView.backgroundColor = [UIColor blueColor];
    }
    return _musicView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view insertSubview:self.musicView aboveSubview:self.musicToolView];
    [self.view insertSubview:self.tabbarView aboveSubview:self.musicView];
    
    [self addGesture];
}


/**
 *  通过NSURLSession 请求数据
 */
-(void)loadDownNetJson{

    //1.创建URL
    NSURL *url = [NSURL URLWithString:@"http://graph.luoo.net/index/random?key=86aef0c62be013159025911a8c79ced1&platform=ios"];
    
    //2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.创建会话(这里使用一个全局会话),并且启动任务
    NSURLSession *session = [NSURLSession sharedSession];
    //从会话创建任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
//            NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"数据请求成功");
        }else{
        
            NSLog(@"error is :%@",error.localizedDescription);
        }
    }];
    
    [dataTask resume];//恢复线程,启动任务
    
}
- (IBAction)down1:(id)sender {

    [self downloadFileByConfiguration:@"http://luoo-mp3.kssws.ks-cdn.com/low/chinese/20160109.mp3" fileName:@"test1.mp3"];
    [MBProgressHUD showSuccess:@"开始下载任务1"];
}

- (IBAction)down2:(id)sender {
    
    [self downloadFileByConfiguration:@"http://luoo-mp3.kssws.ks-cdn.com/low/they/20140228.mp3" fileName:@"test2.mp3"];
    [MBProgressHUD showSuccess:@"开始下载任务2"];
}


#pragma mark - 手势事件

- (void)addGesture
{
    //解决在图片上滑动时拖动手势和轻扫手势的冲突
    [_panMusic requireGestureRecognizerToFail:_swipeMusic];
    
}


- (IBAction)panMusicPlayer:(UIPanGestureRecognizer *)gesture {
    
    CGPoint translation = [gesture translationInView:self.view];
    
    if (gesture.state == UIGestureRecognizerStateChanged) {
        NSLog(@"pan change 手势");
        
        self.musicView.transform = CGAffineTransformMakeTranslation(0, translation.y);
        
        self.tabbarView.transform = CGAffineTransformMakeTranslation(0, -translation.y*(self.tabbarView.bounds.size.height*2/self.view.bounds.size.height));
    }
    else if (gesture.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"pan ended 手势");
        
        if ((-translation.y) >= self.view.bounds.size.height/2) {
            [UIView animateWithDuration:0.5 animations:^{
                self.musicView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
            }];
        }
        else
        {
            [UIView animateWithDuration:0.5 animations:^{
                self.musicView.transform = CGAffineTransformIdentity;
                
                self.tabbarView.transform = CGAffineTransformIdentity;
            }];
        }
    }
}


/**
 *  普通下载
 *
 *  @param downUrl  url
 *  @param fileName 文件名
 */
-(void)downloadFile:(NSString *)downUrl fileName:(NSString *)fileName{
    //1.创建url
    NSURL *url = [NSURL URLWithString:downUrl];
    //2.创建请求
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url];
    //3.创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSError *saveError;
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            NSString *savePath = [cachePath stringByAppendingPathComponent:fileName];
            NSLog(@"savePath --->%@",savePath);
            NSURL *saveUrl = [NSURL fileURLWithPath:savePath];
            [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&saveError];
            if (!saveUrl) {
                NSLog(@"save success");
            }else{
            
                NSLog(@"error is :%@",saveError.localizedDescription);
            }
            
        }else{
            NSLog(@"error is :%@",error.localizedDescription);
        }
        
    }];
    
    [downloadTask resume];
    
}

/**
 *  通过NSURLSessionConfiguration,配置下载,有代理方法,支持监听下载进度,自动网络选择,后台下载,文件下载完毕之后位移
 *
 *  @param downUrl  url
 *  @param fileName 保存文件名
 */
-(void)downloadFileByConfiguration:(NSString *)downUrl fileName:(NSString *)fileName{
    //1.创建url
    NSURL *url = [NSURL URLWithString:downUrl];
    //2.创建请求
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url];
    //3.创建会话
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForRequest = 5.0f;//请求超时时间
    sessionConfig.allowsCellularAccess = true;//是否允许蜂窝网络下载(2G/3G/4G)
    NSURLSession *session  = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理
    session.sessionDescription = fileName;
    _downloadTask = [session downloadTaskWithRequest:request];
    
    [_downloadTask resume];
    
    //读取plist
//    NSString *plistPath = [[NSBundle mainBundle]pathForResource:@"musicDownLoad" ofType:@"plist"];
//    NSMutableDictionary *data =[[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
//    
//    //添加当前数据内容到plist中
//    [data setObject:fileName forKey:@"name"];
//    //获取应用沙盒的Document目录
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *plistPath1 = [paths firstObject];
//    //得到完整的文件名
//    NSString *fileNameThis = [plistPath1 stringByAppendingPathComponent:@"music.plist"];
//    //键入输入
//    [data writeToFile:fileNameThis atomically:YES];
//    
//    NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:fileNameThis];
//    NSLog(@"%@", data1);
    
    
    
}

#pragma mark URLSessionDownload通过配置文件下载方式

-(void)URLSession:(NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{


    NSLog(@"%.2f",(double)totalBytesWritten/totalBytesExpectedToWrite);
    double process =totalBytesWritten/totalBytesExpectedToWrite;
//    if (process == 1.00) {
//        [MBProgressHUD showSuccess:@"下载成功!"];
//        
//    }
    
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

    NSError *saveError;
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *savePath = [cachePath stringByAppendingPathComponent:session.sessionDescription];
    NSURL *saveUrl = [NSURL fileURLWithPath:savePath];
   [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&saveError];
    
    NSString *plistPath = [cachePath stringByAppendingPathComponent:@"music.plist"];
    NSArray *plistArray = [NSArray arrayWithContentsOfFile:plistPath];
    
    
    if (plistArray) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:plistArray];
        [array addObject:@{@"name":session.sessionDescription,@"musicPath":savePath}];
        [array writeToFile:plistPath atomically:YES];
    }
    else
    {
        NSMutableArray *array = [NSMutableArray array];
        [array addObject:@{@"name":session.sessionDescription,@"musicPath":savePath}];
        [array writeToFile:plistPath atomically:YES];
    }
    
    
    
    
}



@end
